//
//  TTPostersViewController.m
//  TaoTuo
//
//  Created by admin on 2019/12/3.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTPostersViewController.h"
#import "LLFluidViewFlowLayout.h"
#import "TTPosterViewCell.h"
#import "TTDianpuShareView.h"
#import <WXApi.h>

static NSString *cellID = @"cell";

@interface TTPostersViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger selectIndex;

@property (nonatomic, strong) TTDianpuShareView *shareView;

@end

@implementation TTPostersViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"分享商城海报";
    self.view.backgroundColor = kSeparatorColor;
    self.selectIndex = 0;
    
    UIImage *image = [[UIImage imageNamed:@"fenxiang"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(shareBtnClick)];
    
    [self getNetworkData];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTPosterViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.urlString = self.dataArray[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@">>>> %ld", indexPath.row);
    [collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    self.selectIndex = indexPath.row;
}


///获取图片信息
- (void)getNetworkData
{
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getShopPoster_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        for (NSString *string in responseObject) {
            [self.dataArray addObject:string];
        }
        
        [self setupSubviews];
        [self.collectionView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

///下载图片到手机
- (void)downloadBtnClick
{
    TTPosterViewCell *cell = (TTPosterViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.selectIndex inSection:0]];
    if (cell.imageView.image) {
        UIImageWriteToSavedPhotosAlbum(cell.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        [MBProgressHUD showError:@"保存失败"];
    } else {
        [MBProgressHUD showSuccess:@"保存成功"];
    }
}

// 分享海报
- (void)shareBtnClick
{
    if (self.shareView == nil) {
        self.shareView = [TTDianpuShareView shareViewWithTitles:@[@"分享海报到朋友圈", @"分享海报给好友"] selectBlock:^(NSInteger index) {
            
            NSString *selStr = [NSString stringWithFormat:@"shareTo_%ld", index];
            SEL sel = NSSelectorFromString(selStr);
            if ([self respondsToSelector:sel]) {
                IMP imp = [self methodForSelector:sel];
                void (*func)(id, SEL) = (void *)imp;
                func(self, sel);
            }
        }];
    }
    
    [LLAnimationAlertView animationAlertViewWithView:self.shareView animationType:AnimationFromBottom];
}

///朋友圈
- (void)shareTo_0
{
    [self shareImageToWeixinWIthType:WXSceneTimeline];
}

///朋友
- (void)shareTo_1
{
    [self shareImageToWeixinWIthType:WXSceneSession];
}

- (void)shareImageToWeixinWIthType:(int)type
{
    TTPosterViewCell *cell = (TTPosterViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.selectIndex inSection:0]];
    if (cell.imageView.image == nil) {
        return;
    }
    
    NSData *imageData = UIImageJPEGRepresentation(cell.imageView.image, 0.7);
       
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = imageData;

    WXMediaMessage *message = [WXMediaMessage message];
    message.mediaObject = imageObject;

    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = type;
    [WXApi sendReq:req completion:^(BOOL success) {
        NSString *str = success ? @"分享成功" : @"分享失败";
        [[UIApplication sharedApplication].keyWindow makeToast:str];
    }];
}


- (void)setupSubviews
{
    UIImageView *selectImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"wancheng"]];
    [self.view addSubview:selectImageView];
    [selectImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).mas_offset(15 * kScale);
        make.centerX.equalTo(self.view);
    }];
    
    UIButton *downloadBtn = [UIButton createButtonWithTitle:@"下载海报" titleColor:UIColorHex(333333) titleFont:[UIFont systemFontOfSize:18] backgroundColor:[UIColor whiteColor] target:self action:@selector(downloadBtnClick)];
    [self.view addSubview:downloadBtn];
    [downloadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottomLayoutGuide);
        make.height.mas_equalTo(45);
        make.left.equalTo(self.view);
        make.width.mas_equalTo(self.view.width * 0.5);
    }];
    
    UIButton *shareBtn = [UIButton createButtonWithTitle:@"立即分享" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor target:self action:@selector(shareBtnClick)];
    [self.view addSubview:shareBtn];
    [shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.width.height.equalTo(downloadBtn);
        make.right.equalTo(self.view);
    }];
    
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        
        LLFluidViewFlowLayout *layout = [[LLFluidViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(260 * kScale, 455 * kScale);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        @weakify(self)
        layout.currentIndexBlock = ^(NSInteger index) {
            @strongify(self)
            self.selectIndex = index;
        };
        
        CGRect rect = CGRectMake(0, 0, self.view.frame.size.width, 460 * kScale);
        _collectionView = [[UICollectionView alloc] initWithFrame:rect collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[TTPosterViewCell class] forCellWithReuseIdentifier:cellID];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


@end
